/**
 * 
 */
package com.hezuti.common.action;


import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.Preparable;

/**
 * @author dxy
 * 
 */
@SuppressWarnings("serial")
public class BaseAction extends ActionSupport implements Preparable {

	/**
	 * 日志
	 */
	protected Log log = LogFactory.getLog(getClass());

	/** CURRENT_URI_NAME */
	public static String CURRENT_URI_NAME = "currentURI";

	private String currentURI;


	/**
	 * 重写父类方法
	 */
	public void prepare() throws Exception {
		currentURI = ServletActionContext.getRequest().getRequestURI();
	}

	/**
	 * 
	 * @return
	 */
	public String getCurrentURI() {
		return currentURI;
	}

	/**
	 * 
	 * @param currentURI
	 */
	public void setCurrentURI(String currentURI) {
		this.currentURI = currentURI;
	}

	/**
	 * 得到httprequest
	 * 
	 * @return
	 */
	public HttpServletRequest getRequest() {
		return ServletActionContext.getRequest();
	}

	/**
	 * 得到httpresponse
	 * 
	 * @return
	 */
	public HttpServletResponse getResponse() {
		return ServletActionContext.getResponse();
	}

	/**
	 * 得到HttpSession
	 * 
	 * @return
	 */
	public HttpSession getSession() {
		return  ServletActionContext.getRequest().getSession();
	}

	/**
	 * 得到一个指定的cookie
	 * 
	 * @param cookieName
	 * @return
	 */
	public Cookie getCookie(String cookieName) {
		HttpServletRequest request = ServletActionContext.getRequest();
		Cookie[] cookies = request.getCookies();
		if (cookies == null)
			return null;
		for (Cookie c : cookies) {
			if (c.getName().equalsIgnoreCase(cookieName))
				return c;
		}
		return null;
	}

	/**
	 * 获取客户端IP
	 * 
	 * @param request
	 * @return
	 */
	protected String getIp() {
		HttpServletRequest request = this.getRequest();
		String ip = request.getHeader("x-forwarded-for");
		if ((ip == null) || (ip.length() == 0) || ("unknown".equalsIgnoreCase(ip))) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if ((ip == null) || (ip.length() == 0) || ("unknown".equalsIgnoreCase(ip))) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if ((ip == null) || (ip.length() == 0) || ("unknown".equalsIgnoreCase(ip))) {
			ip = request.getRemoteAddr();
		}
		return ip;
	}

}
